<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\BaseController;
use App\Models\UserBalanceDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IncomeController extends BaseController
{
    public function total()
    {
        $user_id = auth('api')->id();
        $gift_income_amount = DB::table('user_balance_details')
                                ->where('user_id',$user_id)
                                ->where('type',1)
                                ->sum('amount');

        $ad_income_amount = DB::table('user_balance_details')
            ->where('user_id',$user_id)
            ->where('type',2)
            ->sum('amount');


        $course_income_amount = DB::table('user_balance_details')
            ->where('user_id',$user_id)
            ->where('type',3)
            ->sum('amount');


        $promotion_income_amount = DB::table('user_balance_details')
            ->where('user_id',$user_id)
            ->where('type',4)
            ->sum('amount');

        $balance = DB::table('users')->where('id',$user_id)->value('balance');

        $total_income_amount = DB::table('user_balance_details')
                                ->where('user_id',$user_id)
                                ->sum('amount');


        return $this->success([
            'total_income_amount' => $total_income_amount,
            'gift_income_amount'  => $gift_income_amount,
            'ad_income_amount' => $ad_income_amount,
            'course_income_amount' => $course_income_amount,
            'promotion_income_amount' => $promotion_income_amount,
            'balance' =>  $balance
        ]);
    }


    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'type' => 'in:1,2,3,4'
        ]);

        $query = UserBalanceDetail::query();

        if (isset($param['type'])){
            $query->where('type',$param['type']);
        }

        $user_id = auth('api')->id();

        $incomes = $query->where('user_id',$user_id)
                        ->orderByDesc('id')
                        ->simplePaginate();

        return $this->success($incomes);

    }
}
